﻿// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri(str) {
	var o = parseUri.options,
		m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function(match, first, second) {
		if (first) uri[o.q.name][first] = second;
	});

	return uri;
}

parseUri.options = {
	strictMode: false,
	key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
	q: {
		name: "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

// mini url api
var URL = function(url) {
	if (!url || typeof url != "string")
		throw new Error("invalid url arg");

	var uri = parseUri(url);
	var q = uri.queryKey || {};
	var ps = uri.port ? ':' + uri.port : '';

	return {
		source: uri.source,
		protocol: uri.protocol,
		host: uri.host,
		port: uri.port || '80',
		domain: uri.protocol + '://' + uri.host + ps,
		path: uri.path,
		directory: uri.directory,
		file: uri.file,
		query: $.extend({}, q, {
			get: function(name) {
				var f = Object.keys(q).filter(function(key) {
					return key.toLowerCase() == (name || '').toLowerCase();
				});
				return f.length === 1 ? uri.queryKey[f[0]] : null;
			}
		})
	};
};
